/**
    公用js处理方法
    author by RICK 2015/11/14
 **/
var ART = {};

/**
 * 异步请求
 * @param surl      url地址
 * @param type      默认GET，可选
 * @param params    请求参数,可选
 * @param fnSuccess 成功回调方法,可选
 * @param fnError   失败回调方法,可选
 * @returns {*}
 */
ART.mAjax = function(surl,type,params,fnSuccess,fnError){
    var data = null;
    if(type == null){
        type = "GET";
    }
    if(params == null){
        params = {};
    }
    $.ajax({
        type:type,
        url: surl,
        data:params,
        cache:true,
        async:false,
        success: function(response){
            data = response;
            if(fnSuccess)
                fnSuccess(data);
        },
        error:function(response){
            data = null;
            if(fnError)
                fnError(data);
        }
    });
    return data;
};

/**
 *
 * @param sUrl              加载url
 * @param params            参数
 * @param selObj            select对象
 * @param valueFieldName    value属性名称
 * @param textFieldName     text属性显示值
 * @param hasChoise         是否包含请选择，默认 {valueFieldName:'',textFieldName:"请选择"}
 * @param currentChoise     {valueField:"-1",textField:"全部"}
 */
ART.mLoadSelectOption = function(sUrl,params,selObj,valueFieldName,textFieldName,hasChoise,currentChoise){
    var selData = ART.mAjax(sUrl,"POST",params);
    if(null != selData){
        $(selObj).empty();//set empty
        var defaultValue = $(selObj).attr("def_value");  //default value
        var optionHtml = "";
        var valueField = valueFieldName || "value";
        var textField = textFieldName || "text";
        if(hasChoise && hasChoise == true){
            if(currentChoise){//自定义选择项
                optionHtml += "<option value='"+currentChoise[valueField]+"'>"+currentChoise[textField]+"</option>";
            }else{
                optionHtml += "<option value=''>请选择...</option>";
            }
        }
        $.each(selData,function(index,content){
            var value = content[valueField];
            var selected = value == defaultValue ? "selected='selected'":"";
            optionHtml += "<option value='"+value+"' "+selected+">"+content[textField]+"</option>";
        });
        $(optionHtml).appendTo(selObj);
    }
};

/**
 *
 * @param JsonArray
 * @param selObj
 * @param valueFieldName
 * @param textFieldName
 */
ART.mLoadCustomSelectOption = function(JsonArray,selObj,valueFieldName,textFieldName){
    if(null != JsonArray){
        var defaultValue = $(selObj).attr("def_value");
        var optionHtml = "";
        var valueField = valueFieldName || "value";
        var textField = textFieldName || "text";
        $.each(JsonArray,function(index,content){
            var value = content[valueField];
            var selected = value == defaultValue ? "selected='selected'":"";
            optionHtml += "<option value='"+value+"' "+selected+">"+content[textField]+"</option>";
        });
        $(optionHtml).appendTo(selObj);
    }
};

/**
 * 获取下拉框选择的text
 * @param selObj
 * @returns {*|jQuery}
 */
ART.getSelectedText = function(selObj){
    return $(selObj).find("option:selected").text();
};

/**
 * 选中菜单
 * @param menuId
 */
ART.selectMenu = function(menuId){
    if (localStorage) {
        if(null == menuId){
            localStorage.removeItem("menu")
        }else{
            localStorage.setItem("menu",menuId);
        }
    }
};

/**
 * 获取选中菜单Id
 * @returns {null}
 */
ART.getSelMenu = function(){
    if (localStorage) {
        return localStorage.getItem("menu");
    }else {
        return null;
    }
};

// by limumu
// 文件名由系统后台生成 适用于相同尺寸同一类型多文件上传时使用
function uploadFiles ( arrayInputId , requestURI ) {
    uploadFiles(arrayInputId,requestURI);
}

// by limumu
// 文件名由系统后台生成 适用于相同尺寸同一类型多文件上传时使用
// callback 为 回显提示
function uploadFiles ( arrayInputId , requestURI , callback) {
    uploadFiles(arrayInputId,requestURI,callback);
}

// by limumu
// 文件名由系统后台生成 适用于不同尺寸同一类型多文件上传时使用
// callback 为 回显提示
function uploadFiles ( arrayInputId , requestURI , callback , fileName ) {

    $.ajaxSetup({
        async: false
    });

    // 创建一个 form
    var ajaxSubmitForm = document.createElement("form");
    ajaxSubmitForm.id = "_form";
    ajaxSubmitForm.name = "_form";
    ajaxSubmitForm.enctype = "multipart/form-data" ;
    document.body.appendChild(ajaxSubmitForm);

    // 如果存在fileName
    var fileName = fileName || '';
    if (fileName.replace(/(^s*)|(s*$)/g, "").length != 0) {

        var fileNameInput = document.createElement("input");
        fileNameInput.type = "text";
        fileNameInput.name = "fileName";
        fileNameInput.id = "fileName";
        fileNameInput.value = fileName;
        ajaxSubmitForm.appendChild(fileNameInput);

    }

    if (arrayInputId instanceof Array) {

        for(var element in arrayInputId){

            // 创建一个输入
            var input = document.getElementById(arrayInputId[element]);

            // 将该输入框插入到 form 中
            ajaxSubmitForm.appendChild(input);

        }

    } else {

        // 创建一个输入
        var input = document.getElementById(arrayInputId);

        // 将该输入框插入到 form 中
        ajaxSubmitForm.appendChild(input);

    }

    // 对该 form 执行提交
    $("#_form").ajaxSubmit({
        type : "post",
        url : requestURI ,
        success : function(data) {

            // 删除该 form
            document.body.removeChild(ajaxSubmitForm);

            if( callback && (callback  instanceof Function) ) {
                callback(eval(data)) ;

            }

        },
        error : function(XmlHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });

    return false;

}

// 生成UUID 长度可以指定 uuid(32, 62)
function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;

    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
        // rfc4122, version 4 form
        var r;

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random()*16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}

function generateUUID () {
    return uuid(32, 62) ;
}

//十六进制颜色值域RGB格式颜色值之间的相互转换

//-------------------------------------
//十六进制颜色值的正则表达式
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
/*RGB颜色转换为16进制*/
String.prototype.colorHex = function(){
    var that = this;
    var aColor = that.split(",");
    var strHex = "#";
    for(var i=0; i<aColor.length; i++){
        var hex = Number(aColor[i]).toString(16);
        if(hex === "0"){
            hex += hex;
        }
        strHex += hex;
    }
    if(strHex.length !== 7){
        strHex = that;
    }
    return strHex;
};

//-------------------------------------------------

/*16进制颜色转为RGB格式*/
String.prototype.colorRgb = function(){
    var sColor = this.toLowerCase();
    if(sColor && reg.test(sColor)){
        if(sColor.length === 4){
            var sColorNew = "#";
            for(var i=1; i<4; i+=1){
                sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));
            }
            sColor = sColorNew;
        }
        //处理六位的颜色值
        var sColorChange = [];
        for(var i=1; i<7; i+=2){
            sColorChange.push(parseInt("0x"+sColor.slice(i,i+2)));
        }
        return sColorChange.join(",");
    }else{
        return sColor;
    }
};

$("#go_back_btn").on("click",function(){
    history.back();
    parent.document.location.reload();
});